package rpc05;

import com.hl.rpc.common.User;
import com.hl.rpc.service.IUserService;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

/**
 * Created by yuanhailong on 2021/10/30.
 * 客户端代理对象：屏蔽客户端访问请求时候的细节
 */
public class Stub {

    /**
     * 返回任何代理类
     * @param clazz
     * @return
     * @throws Exception
     */
    public static Object getStub(final Class clazz) throws Exception{
        InvocationHandler invocationHandler = new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Socket socket=new Socket("localhost",9999);

                System.out.println("rpc05 动态代理...");


                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

                /**
                 * 客户端请求的方法名称，类型，和参数传递到服务端，服务端解析后，调用具体方法
                 */
                String methodName=method.getName();
                Class<?>[] parameterTypes = method.getParameterTypes();
                oos.writeUTF(clazz.getName());
                oos.writeUTF(methodName);
                oos.writeObject(parameterTypes);
                oos.writeObject(args);
                oos.flush();

                System.out.println(" class name:"+clazz.getName());
                System.out.println(" method name:"+methodName);


                /**
                 * 获取服务端数据
                 */
                ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
                User user=(User) ois.readObject();
                ois.close();
                socket.close();
                return user;
            }
        };
        //创建动态代理对象
        Object instance = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, invocationHandler);
        return instance;

    }

}
